import { useState, useEffect, useMemo } from 'react';

interface ScreenInfo {
  width: number;
  height: number;
  isMobile: boolean;
  isTablet: boolean;
  isDesktop: boolean;
  breakpoint: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
}

interface BreakpointConfig {
  xs: number;  // 超小屏幕 < 576px
  sm: number;  // 小屏幕 >= 576px
  md: number;  // 中等屏幕 >= 768px
  lg: number;  // 大屏幕 >= 992px
  xl: number;  // 超大屏幕 >= 1200px
  xxl: number; // 超超大屏幕 >= 1400px
}

const defaultBreakpoints: BreakpointConfig = {
  xs: 576,
  sm: 768,
  md: 992,
  lg: 1200,
  xl: 1400,
  xxl: 1600
};

export function useScreenWidth(customBreakpoints?: Partial<BreakpointConfig>): ScreenInfo {
  const breakpoints = useMemo(() => ({ ...defaultBreakpoints, ...customBreakpoints }), [customBreakpoints]);

  const getScreenInfo = useMemo(() => (): ScreenInfo => {
    const width = window.innerWidth;
    const height = window.innerHeight;

    // 判断断点
    let breakpoint: ScreenInfo['breakpoint'] = 'xs';
    if (width >= breakpoints.xxl) breakpoint = 'xxl';
    else if (width >= breakpoints.xl) breakpoint = 'xl';
    else if (width >= breakpoints.lg) breakpoint = 'lg';
    else if (width >= breakpoints.md) breakpoint = 'md';
    else if (width >= breakpoints.sm) breakpoint = 'sm';

    // 判断设备类型
    const isMobile = width < breakpoints.md;
    const isTablet = width >= breakpoints.md && width < breakpoints.lg;
    const isDesktop = width >= breakpoints.lg;

    return {
      width,
      height,
      isMobile,
      isTablet,
      isDesktop,
      breakpoint
    };
  }, [breakpoints]);

  const [screenInfo, setScreenInfo] = useState<ScreenInfo>(() => getScreenInfo());

  useEffect(() => {
    const handleResize = () => {
      setScreenInfo(getScreenInfo());
    };

    // 添加防抖以提高性能
    let timeoutId: NodeJS.Timeout;
    const debouncedHandleResize = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(handleResize, 100);
    };

    window.addEventListener('resize', debouncedHandleResize);

    return () => {
      window.removeEventListener('resize', debouncedHandleResize);
      clearTimeout(timeoutId);
    };
  }, [getScreenInfo]);

  return screenInfo;
}

// 便捷的 Hook 变体
export function useScreenWidthSimple(): number {
  const { width } = useScreenWidth();
  return width;
}

// 断点判断 Hook
export function useBreakpoint(): ScreenInfo['breakpoint'] {
  const { breakpoint } = useScreenWidth();
  return breakpoint;
}

// 设备类型判断 Hook
export function useDeviceType() {
  const { isMobile, isTablet, isDesktop } = useScreenWidth();
  return { isMobile, isTablet, isDesktop };
}
